#include <stdbool.h>
#include <math.h>
#include "redoor.h"

// 初始化函数
void swinging_door_init(SwingingDoorState *state, float deviation, float delta_time) {
    state->prev_value = 0;
    state->max_slope = INFINITY;
    state->min_slope = -INFINITY;
    state->deviation = deviation;
    state->delta_time = (delta_time > 0) ? delta_time : 2.0f; // 处理无效时间间隔
}

// 处理函数
bool swinging_door_process(SwingingDoorState *state, float new_value) {
    if (state->prev_value == 0) {
        state->prev_value = new_value;
        return true; // 首次数据必须发送
    }

    float delta_value = new_value - state->prev_value;
    float delta_time = state->delta_time;
    state->delta_time+=2;
    // 计算新斜率范围
    float upper_slope = (delta_value + state->deviation) / delta_time;
    float lower_slope = (delta_value - state->deviation) / delta_time;

    // 更新斜率限制
    float new_max = fminf(upper_slope, state->max_slope);
    float new_min = fmaxf(lower_slope, state->min_slope);

    if (new_max >= new_min) { // 斜率范围有效则缩小范围
        state->max_slope = new_max;
        state->min_slope = new_min;
        return false;
    } else { // 超出范围则保留当前点并重置
        state->prev_value = new_value;
        state->max_slope = INFINITY;
        state->min_slope = -INFINITY;
        state->delta_time = 2.0f;
        return true;
    }
}


// 初始化所有传感器的状态
void init_sensor_states(SensorStates *states, float deviation, float delta_time) {
    swinging_door_init(&states->temp, deviation, delta_time);
    swinging_door_init(&states->hum, deviation, delta_time);
    swinging_door_init(&states->lig, deviation, delta_time);
    swinging_door_init(&states->soil, deviation, delta_time);
    swinging_door_init(&states->rain, deviation, delta_time);
    swinging_door_init(&states->uv, deviation, delta_time);


}

// 数据压缩判断函数
bool should_send_data(SensorData *data, SensorStates *states) {
    bool send = false;

    // 处理温度
    float temp = atof(data->temperature);
    if (swinging_door_process(&states->temp, temp)) send = true;

    // 处理湿度
    float hum = atof(data->humidity);
    if (swinging_door_process(&states->hum, hum)) send = true;

    // 处理光照
    float lig = atof(data->ligBuffer);
    if (swinging_door_process(&states->lig, lig)) send = true;

    // 处理土壤湿度
    float soil = atof(data->soilHum);
    if (swinging_door_process(&states->soil, soil)) send = true;

    // 处理雨水值
    float rain = atof(data->rain);
    if (swinging_door_process(&states->rain, rain)) send = true;

    // 处理紫外线
    float uv = atof(data->uv);
    if (swinging_door_process(&states->uv, uv)) send = true;
    
    return send;
}